package com.sxygsj.baselibrary.network

import android.content.Context
import android.util.Log
import com.sxygsj.baselibrary.application.BaseApplication


import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import retrofit2.Retrofit
import java.util.concurrent.TimeUnit


/**
 * @Author LD  步骤二、创建API的构建器
 * @Time 2020/8/11 9:39
 * @Describe object代表单例类，只有一个，该类用于创建Retrofit实例
 * @Modify
 */
object ServiceCreator {

    //定义常量base地址，私有的相当于对外部而言是不可见的
    // TODO: 2021/2/26 地址变化了怎么使用
    private const val BASE_URL = "http://192.168.14.57:8080/"


    private val TAG = "ceshi"

    private val httpClient = OkHttpClient.Builder()
//        .addInterceptor(ReceivedCookiesInterceptor())
//        .addInterceptor(AddCookiesInterceptor())
        .connectTimeout(5, TimeUnit.SECONDS)
        .readTimeout(5, TimeUnit.SECONDS)
        .writeTimeout(5, TimeUnit.SECONDS)
        .build()

    //私有的相当于对外部而言是不可见的
    private val retrofit = Retrofit.Builder()
        .baseUrl(BASE_URL)
        .client(httpClient)
        .addConverterFactory(ResponseConverterFactory.create())
        .build()


    //提供一个对外部可见的create方法！！！！！！！
    //使用：val placeService = ServiceCreator.create(PlaceService::class.java)
    fun <T> create(serviceClass: Class<T>): T = retrofit.create(serviceClass)

    //拦截器来拦截Cookies
    class ReceivedCookiesInterceptor : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {
            //拦截的cookie保存在response中
            val request = chain.request()
            val response = chain.proceed(request)
            Log.i(TAG, "intercept: " + response.headers("Set-Cookie").toString())
            Log.i(TAG, "intercept: " + response.headers("sessionID").toString())

            //怎么保存下来
            val cookies: HashSet<String> = HashSet()
//            if(!response.header("Set-Cookie").isNullOrEmpty()){
//
//                for (header in response.headers("Set-Cookie")) {
//                    cookies.add(header)
//                }
//                val sharedPreferences = MyApplication.context.getSharedPreferences(
//                    "cookieData",
//                    Context.MODE_PRIVATE
//                )
//                val editor = sharedPreferences.edit()
//                editor.putStringSet("cookie", cookies)
//                editor.commit()
//            }
            if (!response.header("sessionID").isNullOrEmpty()) {

//                for (header in response.headers("sessionID")) {
//                    Log.i(TAG, "intercept: header为："+header)
////                    cookies.add("$header")
//                    cookies.add(response.header("sessionID")!!)
//                }
                val sharedPreferences = BaseApplication.context.getSharedPreferences(
                    "cookieData",
                    Context.MODE_PRIVATE
                )
                val editor = sharedPreferences.edit()
                editor.putString("cookie", response.header("sessionID"))
//                cookies.add(response.header("sessionID")!!)

                editor.apply()
            }
            return response
        }
    }

    //添加cookies
    class AddCookiesInterceptor : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {
            val builder = chain.request().newBuilder()
//            val cookies =
//                MyApplication.context.getSharedPreferences("cookieData", Context.MODE_PRIVATE)
//                    .getStringSet("cookie", null)
//            if (cookies != null) {
//                for (cookie in cookies) {
//                    builder.addHeader("Cookie", cookie);
//                }
//            }
//            //将cookies添加到请求中
            val cookies =
                BaseApplication.context.getSharedPreferences("cookieData", Context.MODE_PRIVATE)
                    .getString("cookie", "")
//            cookies?.let { builder.addHeader("Cookie", it) }
//            cookies?.let { builder.addHeader("JSESSIONID", it) }
            cookies?.let { builder.addHeader("token", it) }




            Log.i(TAG, "intercept: 添加cookies$cookies")
            return chain.proceed(builder.build())
        }
    }
}